﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using Lottery.Client.SL.Controls;
using Lottery.Client.SL.Util;
using Lottery.Client.Services;

namespace Lottery.Client.SL
{
    public partial class Login : UserControl, IMainPage
    {
        private LoginProgress _loginProgress;
        private DispatcherTimer _timer;

        public Login()
        {
            InitializeComponent();
            PreProcess();
        }

        private void PreProcess()
        {
            ShowInstallOrNot();
            
            Application.Current.CheckAndDownloadUpdateCompleted+=new CheckAndDownloadUpdateCompletedEventHandler(Current_CheckAndDownloadUpdateCompleted);
            Application.Current.CheckAndDownloadUpdateAsync();
        }

        private void Current_CheckAndDownloadUpdateCompleted(object sender, CheckAndDownloadUpdateCompletedEventArgs e)
        {
            Application.Current.CheckAndDownloadUpdateCompleted -= Current_CheckAndDownloadUpdateCompleted;
            //\\ TODO:暂时取消更新
            //if(e.UpdateAvailable)
            //{
            //    this.lbWaiting.Text = "??";
            //    this.progressBarLoading.Visibility = Visibility.Collapsed;
            //    return;
            //}
            if(e.Error!=null)
            {
                MessageBox.Show(e.Error.ToString());
            }
            this.LoadedDone();
        }

        #region IMainPage Members

        public void OpenMain()
        {
            var systemMain = new SystemMain {Name = string.Join("_", Guid.NewGuid().ToString().Split('-'))};
            LayoutRoot.Children.Clear();
           base.Content = systemMain;
           Screen.GetMonitorResolutionAsync((w,h)=>
                                                {
                                                    var mainWindow = Application.Current.MainWindow;
                                                    mainWindow.Left = w - mainWindow.Width;
                                                    mainWindow.Top = 0;

                                                });
        }

        #endregion

        private void LoadedDone()
        {          
            base.KeyDown += (o, e) =>
                                {
                                    if (e.Key == Key.Enter)
                                    {
                                        LoginButton_MouseLeftButtonDown(this, null);
                                    }
                                };
            //_timer = new DispatcherTimer {Interval = TimeSpan.FromSeconds(1.0)};
            //_timer.Tick += _timer_Tick;
            
            CvMainWindow.Visibility = Visibility.Visible;
            gridLoading.Visibility = Visibility.Collapsed;
            lbFindPass.Click += lbFindPass_Click;
            LoginButton.MouseLeftButtonDown += LoginButton_MouseLeftButtonDown;
            hlbtnClear.Click += hlbtnClear_Click;
            //新闻弹窗
            ShowNewsWindowPopup();
        }

        /// <summary>
        /// 新闻弹窗
        /// </summary>
        private void ShowNewsWindowPopup()
        {     
            var newsContent = new NewsContent();
            newsContent.SetHostWindow();
            newsContent.ReadyToShow += (o, a) => newsContent.Show();
        }

        private void hlbtnClear_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Not Implemented!");
        }

        private void LoginButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            string text = tbUserName.Text.Trim();
            string password = tbPasswd.Password;
            if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(password))
            {
                DataCache.CurrentLoginInfo.UserName = text;
                DataCache.CurrentLoginInfo.Password = password;
                DataCache.CurrentLoginInfo.Ver = "";
                _loginProgress = new LoginProgress {ISM = this};
                ProCanvas.Children.Add(_loginProgress);
                _loginProgress.SetWaitCount("正在登录...");
                ConnectAndLogin();
            }
            else
            {
                App.ShowMsg("用户名或密码不能为空！");
            }
        }
        /// <summary>
        /// 登陆服务器
        /// </summary>
        private void ConnectAndLogin()
        {
            var userService = new UserService();
            userService.Loaded +=
                (o, e) =>
                    {
                        var ur = userService.UserInfoResult;
                        if (!string.IsNullOrEmpty(ur.Error))
                        {
                            //登陆失败
                            //App.ShowMsg(Debug.ShowProperty(ur));
                            //_loginProgress.SetWaitCount(string.Format("{0}:{1}",ur.Result,ur.Error));
                            App.ShowMsg(string.Format("{0}:{1}", ur.Result, ur.Error),"登陆失败");
                            _loginProgress.Visibility = Visibility.Collapsed;
                            return;
                        }
                        //建立用户模型
                        DataCache.CurrentLoginInfo.LoginIp = ur.LoginIp;
                        var ui = UserInfo.GetUserInfo(ur);
                        DataCache.CurrentUserInfo = ui;
                        //登陆成功，显示系统主窗体
                        ShowMain(o, EventArgs.Empty);
                    };
            userService.Login(DataCache.CurrentLoginInfo.UserName, DataCache.CurrentLoginInfo.Password);
        }

        private void lbFindPass_Click(object sender, RoutedEventArgs e)
        {
            var findPass = new FindPass();
            findPass.Closed+=(o,a) => 
            findPass.Show();
        }

        private void ShowMain(object sender, EventArgs e)
        {
            PublicFunction.InitLotteryInfo();
            ProCanvas.Children.Remove(_loginProgress);
            OpenMain();
        }
        private void _timer_Tick(object sender, EventArgs e)
        {
            _timer.Stop();
            PublicFunction.InitLotteryInfo();
            ProCanvas.Children.Remove(_loginProgress);
            OpenMain();
        }

        private void ShowInstallOrNot()
        {
            InstallState installState = Application.Current.InstallState;
            if (installState == InstallState.Installed)
            borderInstall.Visibility = Visibility.Collapsed;
        }

        private void btnClose_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Window mainWindow = Application.Current.MainWindow;
            mainWindow.Close();
        }

        private void WindowDragMove_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Window mainWindow = Application.Current.MainWindow;
            mainWindow.DragMove();
        }

        private void Minimized_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Window mainWindow = Application.Current.MainWindow;
            mainWindow.WindowState = WindowState.Minimized;
        }

        private void btClose_Click(object sender, RoutedEventArgs e)
        {
            btnClose_MouseLeftButtonDown(this, null);
        }

        private void btInstall_Click(object sender, RoutedEventArgs e)
        {
            InstallState installState = Application.Current.InstallState;
            try
            {
                Application.Current.Install();
            }
            catch (InvalidOperationException exception)
            {
                MessageBox.Show(exception.InnerException != null
                                    ? exception.InnerException.ToString()
                                    : exception.ToString());
            }
        }
    }
}